package org.jawa;

import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;

import org.apache.commons.configuration.XMLConfiguration;
import org.jawa.util.ClassUtils;

/**
 * Constant values used throughout the application.
 * 
 * <p>
 * <a href="Constants.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:migrant423@gmail.com">JAWA-SHOP</a>
 */
public class Constants {

	public static final String BUNDLE_KEY = "messages";

	/** 当前系统的分隔符 */
	public static final String FILE_SEP = System.getProperty("file.separator");

	/** 当前系统的用户目录 */
	public static final String USER_HOME = System.getProperty("user.home")
			+ FILE_SEP;
	/** 系统的配制文件 */
	public static final String CONFIG_FILENAME = File.separator
			+ "JAWA-SHOP.config";

	private static Locale locale = null;

	private static ApplicationState applicationState = null;

	private static XMLConfiguration XMLConfig = null;

	private static TimeZone timeZone = null;

	/**
     * 新注册用户属性范围
     */
    public static final String REGISTERED = "registered";
    
	/**
	 * JAWA-SHOP安装的目录
	 */
	private static String home = null;

	private Constants() {
	}

	/**
	 * 获取系统配置文件中的locale属性的值,如果为空，返回系统的默认LOCAL
	 * 
	 * @return 返回<tt> Locale 对象</tt>
	 */
	public static Locale getLocale() {
		if (locale == null) {
			if (XMLConfig == null) {
				loadSetupProperties();
			}
			if (XMLConfig != null) {
				String[] localeArray;
				String localeProperty = null;
				try {
					localeProperty = XMLConfig.getProperty("locale").toString();
				} catch (Exception e) {
					localeProperty = null;
				}
				if (localeProperty != null) {
					localeArray = localeProperty.split("_");
				} else {
					localeArray = new String[] { "", "" };
				}
				String language = localeArray[0];
				if (language == null) {
					language = "";
				}
				String country = "";
				if (localeArray.length == 2) {
					country = localeArray[1];
				}

				if (language.equals("") && country.equals("")) {
					locale = Locale.getDefault();
				} else {
					locale = new Locale(language, country);
				}
			} else {
				return Locale.getDefault();
			}
		}
		return locale;
	}

	/**
	 * 设置系统配置文件中的locale属性的值
	 * 
	 * @param newLocale
	 *            <tt>Locale 对象</tt>
	 */
	public static void setLocale(Locale newLocale) {
		locale = newLocale;
		setXMLProperty("locale", locale.toString());
	}

	/**
	 * 获取当前时区 default time zone.
	 * 
	 * @return <tt>返回 TimeZone 类型</tt>
	 */
	public static TimeZone getTimeZone() {
		if (timeZone == null) {
			if (XMLConfig != null) {
				String timeZoneID = (String) XMLConfig
						.getProperty("locale.timeZone");
				if (timeZoneID == null) {
					timeZone = TimeZone.getDefault();
				} else {
					timeZone = TimeZone.getTimeZone(timeZoneID);
				}
			} else {
				return TimeZone.getDefault();
			}
		}
		return timeZone;
	}

	/**
	 * 获取指定结点的属性值
	 * 
	 * @param name
	 *            要获取的结点名称
	 * @return 返回<tt>String 类型值</tt>
	 */
	public static String getXMLProperty(String name) {
		if (XMLConfig == null) {
			loadSetupProperties();
		}

		// home not loaded?
		if (XMLConfig == null) {
			return null;
		}

		return XMLConfig.getProperty(name).toString();
	}

	/**
	 * 获取指定结点的属性值,如果值不存在，返回 <tt>defaultValue</tt>
	 * 
	 * @param name
	 *            要获取的结点名称
	 * @return 返回<tt>String 类型值</tt>
	 */

	public static String getXMLProperty(String name, String defaultValue) {
		if (XMLConfig == null) {
			loadSetupProperties();
		}

		// home not loaded?
		if (XMLConfig == null) {
			return null;
		}

		String value = XMLConfig.getProperty(name).toString();
		if (value == null) {
			value = defaultValue;
		}
		return value;
	}

	/**
	 * 获取指定结点的属性值,如果值不存在，返回 <tt>defaultValue</tt>
	 * 
	 * @param name
	 *            要获取的结点名称
	 * @return 返回<tt>boolean 类型值</tt>
	 */
	public static boolean getXMLProperty(String name, boolean defaultValue) {
		if (XMLConfig == null) {
			loadSetupProperties();
		}

		// home not loaded?
		if (XMLConfig == null) {
			return false;
		}

		String value = XMLConfig.getProperty(name).toString();
		if (value == null) {
			value = "false";
		}
		return Boolean.valueOf(value);
	}

	/**
	 * 设置系统配置文件
	 * 
	 * @param name
	 *            要设置的名称
	 * @param value
	 *            　要设置的值
	 */
	public static void setXMLProperty(String name, String value) {
		if (XMLConfig == null) {
			loadSetupProperties();
		}
		if (XMLConfig != null) {
			XMLConfig.setProperty(name, value);
			try {
				XMLConfig.save();
			} catch (Exception e) {
				XMLConfig = null;
			}
		}
	}

	/**
	 * 判断是否已经安装
	 * 
	 * @return 返回<tt>Boolean 型，true：表示安装，false：表示未安装</tt>
	 */
	private static Boolean isSetupModel() {
		Boolean isSetup = false;
		if (XMLConfig == null) {
			loadSetupProperties();
		}
		if (XMLConfig != null) {
			try {
				Object value = XMLConfig.getProperty("setup");
				if (value == null || "".equals(String.valueOf(value))) {
					isSetup = true;
				} else {
					if ("false".equals(String.valueOf(value))) {
						isSetup = false;
					} else {
						isSetup = true;
					}
				}
			} catch (Exception e) {
				isSetup = true;
			}
		}
		return isSetup;
	}

	/**
	 * 初始化系统配置文件读取类
	 */
	private synchronized static void loadSetupProperties() {
		if (XMLConfig == null) {
			try {
				String resourcePath = getHomeDirectory()+CONFIG_FILENAME;
				XMLConfig = new XMLConfiguration(resourcePath);
			} catch (Exception e) {
				XMLConfig = null;
			}
		}
	}

	/**
	 * 获取当前应用的运行状态
	 * 
	 * @return 返回 <tt>ApplicationState 型</tt>
	 */
	public static ApplicationState getApplicationState() {
		if (null == applicationState) {
			applicationState = ApplicationState.SETUP;
			if (XMLConfig == null) {
				loadSetupProperties();
			}
			if (XMLConfig != null) {
				try {
					Object value = XMLConfig.getProperty("applicationState");
					if (value == null || "".equals(String.valueOf(value))) {
						applicationState = ApplicationState.SETUP;
					} else {
						if ("SETUP".equals(String.valueOf(value))) {
							applicationState = ApplicationState.SETUP;
						} else if ("RUNNING".equals(String.valueOf(value))) {
							applicationState = ApplicationState.RUNNING;
						}else if ("RESTART".equals(String.valueOf(value))) {
							applicationState = ApplicationState.RESTART;
						}else{
							applicationState = ApplicationState.SETUP;
						}
					}
				} catch (Exception e) {
					applicationState = ApplicationState.SETUP;
				}
			}
		}
		return applicationState;
	}

	/**
	 * 设置当前应用的运行状态
	 * 
	 * @param applicationState
	 */
	public static void setApplicationState(ApplicationState applicationState) {
		Constants.applicationState = applicationState;
		setXMLProperty("applicationState", applicationState.toString());
	}
	
	/**
	 * 设置当前应用的运行状态为重启，并不写入配置文件中
	 * 
	 * @param applicationState
	 */
	public static void setApplicationStateRestart() {
		Constants.applicationState = ApplicationState.RESTART;
	}

	/**
	 * Returns the location of the <code>home</code> directory.
	 * 
	 * @return the location of the home dir.
	 */
	public static String getHomeDirectory() {
		if (home == null) {
		}
		return home;
	}

	/**
     * Converts a locale string like "en", "en_US" or "en_US_win" to a Java
     * locale object. If the conversion fails, null is returned.
     *
     * @param localeCode the locale code for a Java locale. See the {@link java.util.Locale}
     *                   class for more details.
     * @return The Java Locale that matches the locale code, or <tt>null</tt>.                  
     */
    public static Locale localeCodeToLocale(String localeCode) {
        Locale locale = null;
        if (localeCode != null) {
            String language = null;
            String country = null;
            String variant = null;
            StringTokenizer tokenizer = new StringTokenizer(localeCode, "_");
            if (tokenizer.hasMoreTokens()) {
                language = tokenizer.nextToken();
                if (tokenizer.hasMoreTokens()) {
                    country = tokenizer.nextToken();
                    if (tokenizer.hasMoreTokens()) {
                        variant = tokenizer.nextToken();
                    }
                }
            }
            locale = new Locale(language,
                    ((country != null) ? country : ""),
                    ((variant != null) ? variant : ""));
        }
        return locale;
    }
    
	/**
	 * Sets the location of the <code>home</code> directory. The directory must
	 * exist and the user running the application must have read and write
	 * permissions over the specified directory.
	 * 
	 * @param pathname
	 *            the location of the home dir.
	 */
	public static void setHomeDirectory(String pathname) {
		File mh = new File(pathname);
		// Do a permission check on the new home directory
		if (!mh.exists()) {
			// Log.error("Error - the specified home directory does not exist ("
			// + pathname + ")");
		} else if (!mh.canRead() || !mh.canWrite()) {
			//Log.error("Error - the user running this application can not read "
			// +
			// "and write to the specified home directory (" + pathname + "). "
			// +
			// "Please grant the executing user read and write permissions.");
		} else {
			home = pathname;
		}
	}

}
